﻿
/*
'===============================================================================
'  MP.LayerHelper.MP_OBS.BL.MaDepartmentManager
'===============================================================================
*/

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using MP.LayerHelper.MP_OBS.BLL;
using MP.LayerHelper.MP_OBS.DAL;
using MP.LayerHelper.MP_OBS.DAL.EntityClasses;
using MP.LayerHelper.MP_OBS.DAL.FactoryClasses;
using MP.LayerHelper.MP_OBS.DAL.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using MP.Core.Library;

namespace MP.LayerHelper.MP_OBS.BLL
{
	public class MaDepartmentManager : MaDepartmentManagerBase
	{
		/// <summary>
		/// Purpose: Class constructor.
		/// </summary>
		public MaDepartmentManager()
		{
			// Nothing for now.
		}
		
		/// <summary>
		/// Method to create an instance of MaDepartmentManager
		/// </summary>
		/// <returns>An instant of MaDepartmentManager class</returns>
		public static MaDepartmentManager CreateInstant()
		{
			return new MaDepartmentManager();
		}

        /// <summary>
        /// Lấy đối tượng phòng ban theo mã Id
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public MaDepartmentEntity GetById(Guid Id)
        {
            EntityCollection<MaDepartmentEntity> items = SelectByIdLST(Id);
            if (items != null && items.Count > 0)
                return (items[0]);
            return null;
        }

        public MaDepartmentEntity GetByName(string name)
        {
            string strSQL = @"Select * From maDepartment Where IsDeleted=0 ";
            string tmpSQL = "";
            tmpSQL += " and dbo.[ufn_Compare](@DepartName,DepartName)=1 ";
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@DepartName", name);
            strSQL += tmpSQL;

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL, param);
            MaDepartmentEntity obj = null;
            while (dr.Read())
            {
                obj = new MaDepartmentEntity();
                obj.Id = (Guid)dr["ID"];
                if (!string.IsNullOrEmpty(dr["DepartCode"].ToString().Trim()))
                    obj.DepartCode = (string)dr["DepartCode"];
                if (!string.IsNullOrEmpty(dr["DepartName"].ToString().Trim()))
                    obj.DepartName = (string)dr["DepartName"];
                if (!string.IsNullOrEmpty(dr["Priority"].ToString().Trim()))
                    obj.Priority = (int)dr["Priority"];
                if (!string.IsNullOrEmpty(dr["Description"].ToString().Trim()))
                    obj.Description= (string)dr["Description"];
                if (!string.IsNullOrEmpty(dr["CreatedBy"].ToString().Trim()))
                    obj.CreatedBy = (string)dr["CreatedBy"];
                if (!string.IsNullOrEmpty(dr["CreatedDate"].ToString().Trim()))
                    obj.CreatedDate = (DateTime)dr["CreatedDate"];
                if (!string.IsNullOrEmpty(dr["UpdatedBy"].ToString().Trim()))
                    obj.UpdatedBy = (string)dr["UpdatedBy"];
                if (!string.IsNullOrEmpty(dr["UpdatedDate"].ToString().Trim()))
                    obj.UpdatedDate = (DateTime)dr["UpdatedDate"];
                obj.IsDeleted = (bool)dr["IsDeleted"];
            }
            dr.Close();
            return obj;
        }
        /// <summary>
        /// Lấy đối tượng phòng ban theo mã code
        /// </summary>
        /// <param name="departCode"></param>
        /// <returns></returns>
        public MaDepartmentEntity GetByDepartCode(string departCode)
        {
            EntityCollection<MaDepartmentEntity> items = new EntityCollection<MaDepartmentEntity>();

            IPredicateExpression predicate = new PredicateExpression();
            predicate.Add(MaDepartmentFields.DepartCode == departCode);
            predicate.Add(MaDepartmentFields.IsDeleted == 0);

            RelationPredicateBucket filter = new RelationPredicateBucket();
            filter.PredicateExpression.Add(predicate);

            using (DataAccessAdapterBase adapter = new DataAccessAdapterFactory().CreateAdapter())
            {
                adapter.FetchEntityCollection(items, filter);
            }

            if (items != null && items.Count > 0)
                return items[0];
            return null;
        }

        /// <summary>
        /// Kiểm tra mã phòng ban tồn tại
        /// </summary>
        /// <param name="departCode"></param>
        /// <returns></returns>
        public bool IsExistsByDepartCode(string departCode)
        {
            MaDepartmentEntity depart = GetByDepartCode(departCode);
            if (depart != null)
                return true;
            return false;
        }
       
        /// <summary>
        /// Lấy danh sách phòng ban, sắp xếp theo độ ưu tiên và tên
        /// </summary>
        /// <returns></returns>
        public DataSet GetAllDepart()
        {
            string strSQL = "Select * " +
                            "From maDepartment " +
                            "Where IsDeleted=0 " +
                            "Order By Priority, DepartName";
            return SqlHelper.ExecuteDataSet(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL);
        }

        /// <summary>
        /// Cập nhật độ ưu tiên
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="priority"></param>
        public void UpdatePriority(Guid Id, int priority)
        {
            string strSQL = "Update maDepartment " +
                            "Set Priority=@Priority " +
                            "Where Id=@Id";
            SqlParameter[] param = new SqlParameter[2];
            param[0] = new SqlParameter("@Priority", priority);
            param[1] = new SqlParameter("@Id", Id);
            SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL, param);
        }

        public DataTable GetByUserId(string UserId)
        {
            string strSQL = "select d.* "+
                            "from (maDepartment as d inner join hrHumanOrganize as h on d.Id=h.DepartId and d.isDeleted=0 and h.IsDeleted=0) " +
                            "inner join hrPosition as p on p.OrganizeId=h.Id and p.UserId=@UserId and p.IsDeleted=0";
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@UserId", UserId);
            return SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL, param);
        }

        public DataTable GetDepartsByDepartCode(string DepartCode)
        {
            string strSQL = " SELECT * " + 
                            " FROM maDepartment " + 
                            " WHERE DepartCode LIKE '" + DepartCode + "%' ";
            return SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.Text, strSQL);
        }

        public Guid GetDepartMaster(string userId)
        {
            string strSQL = "spHR_POSITION_GetDepartMaster";
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@userId", userId);
            DataTable tbl = SqlHelper.ExecuteDataTable(SqlHelper.ConnectionStringOBS, CommandType.StoredProcedure, strSQL, param);
            if (tbl.Rows.Count > 0)
            {
                return new Guid(tbl.Rows[0]["ID"].ToString());
            }
            return Guid.Empty;
        }
	}
}
